<template>
  <div
    class="screen-adapter"
    :class="[
      `screen-adapter--${mode}`,
      {
        'screen-adapter--ready': isReady,
        'screen-adapter--loading': !isReady && showLoading,
        'screen-adapter--debug': showDebugInfo,
      },
    ]"
  >
    <!-- 大屏容器 -->
    <div ref="screenContainer" class="screen-container" :style="containerStyle">
      <!-- 加载状态 -->
      <div v-if="!isReady && showLoading" class="screen-loading" :class="loadingClass">
        <slot name="loading" :loading-text="loadingText">
          <div class="default-loading">
            <div class="loading-spinner" :style="spinnerStyle"></div>
            <p class="loading-text" :style="loadingTextStyle">{{ loadingText }}</p>
          </div>
        </slot>
      </div>

      <!-- 主要内容 -->
      <div v-show="isReady || !showLoading" class="screen-content" :class="contentClass">
        <slot :scale-info="currentScaleInfo" :is-ready="isReady"></slot>
      </div>

      <!-- 错误状态 -->
      <div v-if="hasError" class="screen-error" :class="errorClass">
        <slot name="error" :error="errorInfo" :retry="handleRetry">
          <div class="default-error">
            <div class="error-icon">⚠️</div>
            <p class="error-message">{{ errorInfo.message || "大屏加载失败" }}</p>
            <button class="error-retry-btn" @click="handleRetry">重试</button>
          </div>
        </slot>
      </div>

      <!-- 调试信息 -->
      <div v-if="showDebugInfo" class="debug-panel" :class="debugClass" :style="debugStyle">
        <slot name="debug" :debug-info="debugInfo">
          <div class="debug-content">
            <h4>🔧 调试信息</h4>
            <div class="debug-item">
              <span>设计尺寸:</span>
              <span>{{ designWidth }} × {{ designHeight }}</span>
            </div>
            <div class="debug-item">
              <span>当前窗口:</span>
              <span>{{ currentWidth }} × {{ currentHeight }}</span>
            </div>
            <div class="debug-item">
              <span>缩放比例:</span>
              <span>{{ currentScaleInfo.ratio?.toFixed(3) || "N/A" }}</span>
            </div>
            <div class="debug-item">
              <span>适配模式:</span>
              <span>{{ mode }}</span>
            </div>
            <div class="debug-item">
              <span>设备类型:</span>
              <span>{{ deviceType }}</span>
            </div>
            <div class="debug-item">
              <span>像素比:</span>
              <span>{{ pixelRatio }}</span>
            </div>
            <div class="debug-actions">
              <button @click="refresh" class="debug-btn">刷新适配</button>
              <button @click="toggleMode" class="debug-btn">切换模式</button>
            </div>
          </div>
        </slot>
      </div>
    </div>

    <!-- 全屏背景（可选） -->
    <div v-if="fullscreen && background" class="screen-background" :style="backgroundStyle"></div>
  </div>
</template>

<script>
import { ScreenAdapter, screenUtils } from "./utils/screenAdapter.js";

export default {
  name: "ScreenAdapter",
  props: {
    // 基础配置
    designWidth: {
      type: Number,
      default: 1920,
    },
    designHeight: {
      type: Number,
      default: 1080,
    },
    mode: {
      type: String,
      default: "scale",
      validator: (value) => ["scale", "fit", "full", "rem"].includes(value),
    },

    // 缩放限制
    maxScale: {
      type: Number,
      default: 3,
    },
    minScale: {
      type: Number,
      default: 0.3,
    },

    // rem配置
    remBase: {
      type: Number,
      default: 16,
    },

    // 防抖配置
    debounceTime: {
      type: Number,
      default: 100,
    },

    // 显示配置
    showLoading: {
      type: Boolean,
      default: true,
    },
    loadingText: {
      type: String,
      default: "大屏加载中...",
    },
    autoInit: {
      type: Boolean,
      default: true,
    },

    // 调试配置
    debug: {
      type: Boolean,
      default: false,
    },
    debugPosition: {
      type: String,
      default: "top-right",
      validator: (value) =>
        ["top-left", "top-right", "bottom-left", "bottom-right"].includes(value),
    },

    // 样式配置
    fullscreen: {
      type: Boolean,
      default: true,
    },
    background: {
      type: String,
      default: "",
    },
    transition: {
      type: String,
      default: "all 0.3s ease",
    },

    // 自定义样式类
    containerClass: {
      type: [String, Array, Object],
      default: "",
    },
    contentClass: {
      type: [String, Array, Object],
      default: "",
    },
    loadingClass: {
      type: [String, Array, Object],
      default: "",
    },
    errorClass: {
      type: [String, Array, Object],
      default: "",
    },
    debugClass: {
      type: [String, Array, Object],
      default: "",
    },

    // 错误处理
    errorRetryTimes: {
      type: Number,
      default: 3,
    },
  },

  data() {
    return {
      // 适配器实例
      adapter: null,

      // 状态管理
      isReady: false,
      hasError: false,
      errorInfo: {},
      retryCount: 0,

      // 适配数据
      currentWidth: 0,
      currentHeight: 0,
      currentScaleInfo: {
        scaleX: 1,
        scaleY: 1,
        ratio: 1,
        mode: "scale",
      },

      // 设备信息
      deviceType: "desktop",
      pixelRatio: 1,

      // 调试信息
      showDebugInfo: false,
    };
  },

  computed: {
    // 容器样式
    containerStyle() {
      if (!this.isReady && !this.currentScaleInfo.scaleX) {
        return {
          width: `${this.designWidth}px`,
          height: `${this.designHeight}px`,
          visibility: "hidden",
        };
      }

      const baseStyle = {
        width: `${this.designWidth}px`,
        height: `${this.designHeight}px`,
        transformOrigin: "0 0",
        transition: this.transition,
      };

      if (this.fullscreen) {
        baseStyle.position = "fixed";
        baseStyle.left = "50%";
        baseStyle.top = "50%";
        baseStyle.zIndex = 100;
      }

      // 应用缩放变换
      if (this.mode !== "rem") {
        const { scaleX, scaleY } = this.currentScaleInfo;
        baseStyle.transform = this.fullscreen
          ? `scale(${scaleX}, ${scaleY}) translate(-50%, -50%)`
          : `scale(${scaleX}, ${scaleY})`;
      } else if (this.fullscreen) {
        baseStyle.transform = "translate(-50%, -50%)";
      }

      return baseStyle;
    },

    // 背景样式
    backgroundStyle() {
      if (!this.background) return {};

      return {
        position: "fixed",
        top: 0,
        left: 0,
        width: "100vw",
        height: "100vh",
        zIndex: -1,
        backgroundImage: `url(${this.background})`,
        backgroundSize: "cover",
        backgroundPosition: "center",
        backgroundRepeat: "no-repeat",
      };
    },

    // 加载器样式
    spinnerStyle() {
      const scale = Math.min(this.currentScaleInfo.ratio || 1, 1);
      return {
        transform: `scale(${scale})`,
      };
    },

    loadingTextStyle() {
      const scale = Math.min(this.currentScaleInfo.ratio || 1, 1);
      return {
        transform: `scale(${scale})`,
      };
    },

    // 调试面板样式
    debugStyle() {
      const positions = {
        "top-left": { top: "10px", left: "10px" },
        "top-right": { top: "10px", right: "10px" },
        "bottom-left": { bottom: "10px", left: "10px" },
        "bottom-right": { bottom: "10px", right: "10px" },
      };

      return {
        position: "fixed",
        zIndex: 9999,
        ...positions[this.debugPosition],
      };
    },

    // 调试信息
    debugInfo() {
      return {
        designSize: { width: this.designWidth, height: this.designHeight },
        currentSize: { width: this.currentWidth, height: this.currentHeight },
        scaleInfo: this.currentScaleInfo,
        deviceType: this.deviceType,
        pixelRatio: this.pixelRatio,
        mode: this.mode,
      };
    },
  },

  watch: {
    mode: {
      handler(newMode) {
        if (this.adapter) {
          this.adapter.updateOptions({ mode: newMode });
        }
      },
      immediate: false,
    },

    debug: {
      handler(value) {
        this.showDebugInfo = value && process.env.NODE_ENV === "development";
      },
      immediate: true,
    },
  },

  methods: {
    // 初始化适配器
    initAdapter() {
      try {
        this.adapter = new ScreenAdapter({
          designWidth: this.designWidth,
          designHeight: this.designHeight,
          mode: this.mode,
          maxScale: this.maxScale,
          minScale: this.minScale,
          remBase: this.remBase,
        });

        // 监听适配变化
        this.adapter.onResize(this.handleAdaptChange);

        // 初始化适配器
        this.adapter.init();

        // 获取设备信息
        this.updateDeviceInfo();

        this.$emit("adapter-created", this.adapter);
      } catch (error) {
        this.handleError(error, "初始化适配器失败");
      }
    },

    // 处理适配变化
    handleAdaptChange(adaptData) {
      try {
        const { scaleInfo } = adaptData;

        this.currentWidth = scaleInfo.windowWidth;
        this.currentHeight = scaleInfo.windowHeight;
        this.currentScaleInfo = scaleInfo;

        // 首次加载完成
        if (!this.isReady) {
          this.$nextTick(() => {
            this.isReady = true;
            this.hasError = false;
            this.$emit("ready", adaptData);
          });
        }

        this.$emit("scale-change", adaptData);
      } catch (error) {
        this.handleError(error, "处理适配变化失败");
      }
    },

    // 更新设备信息
    updateDeviceInfo() {
      this.deviceType = screenUtils.getDeviceType();
      this.pixelRatio = screenUtils.getPixelRatio();
    },

    // 错误处理
    handleError(error, message = "未知错误") {
      console.error(message, error);

      this.hasError = true;
      this.errorInfo = {
        message: message,
        error: error,
        timestamp: new Date().toISOString(),
      };

      this.$emit("error", this.errorInfo);
    },

    // 重试机制
    handleRetry() {
      if (this.retryCount >= this.errorRetryTimes) {
        this.$emit("retry-failed", this.retryCount);
        return;
      }

      this.retryCount++;
      this.hasError = false;
      this.isReady = false;

      this.$emit("retry", this.retryCount);

      // 重新初始化
      this.$nextTick(() => {
        this.destroy();
        this.initAdapter();
      });
    },

    // 刷新适配
    refresh() {
      if (this.adapter) {
        this.adapter.updateOptions({
          designWidth: this.designWidth,
          designHeight: this.designHeight,
          mode: this.mode,
          maxScale: this.maxScale,
          minScale: this.minScale,
        });
        this.updateDeviceInfo();
      }
    },

    // 切换模式（调试用）
    toggleMode() {
      const modes = ["scale", "fit", "full"];
      const currentIndex = modes.indexOf(this.mode);
      const nextMode = modes[(currentIndex + 1) % modes.length];
      this.$emit("update:mode", nextMode);
    },

    // 手动设置模式
    setMode(mode) {
      if (["scale", "fit", "full", "rem"].includes(mode)) {
        this.$emit("update:mode", mode);
      }
    },

    // 获取当前适配信息
    getAdaptInfo() {
      return this.adapter ? this.adapter.getCurrentScale() : null;
    },

    // 销毁适配器
    destroy() {
      if (this.adapter) {
        this.adapter.destroy();
        this.adapter = null;
      }
    },
  },

  mounted() {
    if (this.autoInit) {
      this.initAdapter();
    }
  },

  beforeDestroy() {
    this.destroy();
  },
};
</script>

<style lang="less" scoped>
.screen-adapter {
  position: relative;

  &--debug {
    .debug-panel {
      opacity: 1;
    }
  }
}

.screen-container {
  position: relative;
  overflow: hidden;
}

.screen-content {
  width: 100%;
  height: 100%;
  position: relative;
}

// 加载状态
.screen-loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  z-index: 1000;

  .default-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16px;

    .loading-spinner {
      width: 40px;
      height: 40px;
      border: 3px solid rgba(255, 255, 255, 0.3);
      border-top: 3px solid #409eff;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }

    .loading-text {
      margin: 0;
      color: #409eff;
      font-size: 16px;
      font-weight: 500;
    }
  }
}

// 错误状态
.screen-error {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  z-index: 1001;

  .default-error {
    padding: 20px;
    background: rgba(245, 108, 108, 0.1);
    border: 1px solid #f56c6c;
    border-radius: 8px;

    .error-icon {
      font-size: 48px;
      margin-bottom: 12px;
    }

    .error-message {
      color: #f56c6c;
      margin: 0 0 16px 0;
      font-size: 14px;
    }

    .error-retry-btn {
      background: #f56c6c;
      color: white;
      border: none;
      padding: 8px 16px;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;

      &:hover {
        background: #f78989;
      }
    }
  }
}

// 调试面板
.debug-panel {
  background: rgba(0, 0, 0, 0.85);
  color: #fff;
  padding: 12px;
  border-radius: 6px;
  font-family: "Consolas", "Monaco", monospace;
  font-size: 12px;
  min-width: 200px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);

  .debug-content {
    h4 {
      margin: 0 0 8px 0;
      font-size: 14px;
      color: #409eff;
    }

    .debug-item {
      display: flex;
      justify-content: space-between;
      margin: 4px 0;
      padding: 2px 0;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);

      span:first-child {
        color: #a0a0a0;
      }

      span:last-child {
        color: #67c23a;
        font-weight: bold;
      }
    }

    .debug-actions {
      margin-top: 8px;
      display: flex;
      gap: 6px;

      .debug-btn {
        background: #409eff;
        color: white;
        border: none;
        padding: 4px 8px;
        border-radius: 3px;
        cursor: pointer;
        font-size: 11px;
        flex: 1;

        &:hover {
          background: #66b1ff;
        }
      }
    }
  }
}

// 动画
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

// 响应式适配
@media screen and (max-width: 768px) {
  .debug-panel {
    font-size: 10px;
    padding: 8px;
    min-width: 150px;
  }

  .screen-loading .default-loading {
    .loading-spinner {
      width: 30px;
      height: 30px;
    }

    .loading-text {
      font-size: 14px;
    }
  }
}

// 高分辨率优化
@media screen and (min-resolution: 2dppx) {
  .screen-content {
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
  }
}
</style>
